﻿namespace Common
{
    using System;
    using System.IO;
    using System.Text;
    using System.Web;

    public class FileHelper
    {
        public static void AppendFile(string _content, string path)
        {
            AppendFile(_content, path, Encoding.Default);
        }

        public static void AppendFile(string _content, string path, Encoding encoding)
        {
            try
            {
                int length = path.LastIndexOf(@"\");
                if (length != -1)
                {
                    string str = path.Substring(0, length);
                    if (!Directory.Exists(str))
                    {
                        Directory.CreateDirectory(str);
                    }
                    using (FileStream stream = new FileStream(path, FileMode.Append))
                    {
                        byte[] bytes = encoding.GetBytes(_content);
                        stream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new Exception("往文件'" + path + "'追加内容失败。错误信息：" + exception.Message);
            }
        }

        public static string BuildFileNameByTime(string _srcName)
        {
            return BuildFileNameByTime(_srcName, "");
        }

        public static string BuildFileNameByTime(string _srcName, string _tgtName)
        {
            string str;
            DateTime now = DateTime.Now;
            if ((_tgtName != null) & (_tgtName.Trim().Length > 0))
            {
                str = _tgtName;
            }
            else
            {
                str = now.Year.ToString() + now.Month.ToString() + now.Day.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString() + now.Millisecond.ToString();
            }
            return (str + GetSuffix(_srcName));
        }

        public static void CreateDirectory(string path)
        {
            try
            {
                path = path.Replace("/", @"\");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch (Exception exception)
            {
                throw new Exception("在'" + path + "'下创建目录失败。错误信息：" + exception.Message);
            }
        }

        public static void DeleteFolder(string dir)
        {
            try
            {
                foreach (string str in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(str))
                    {
                        FileInfo info = new FileInfo(str);
                        if (info.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        {
                            info.Attributes = FileAttributes.Normal;
                        }
                        File.Delete(str);
                    }
                    else
                    {
                        DeleteFolder(str);
                    }
                }
                Directory.Delete(dir);
            }
            catch
            {
            }
        }

        public static void FileDownload(string FullFileName, string RealFileName)
        {
            FileInfo info = new FileInfo(FullFileName);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Buffer = false;
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(RealFileName, Encoding.UTF8));
            HttpContext.Current.Response.AppendHeader("Content-Length", info.Length.ToString());
            HttpContext.Current.Response.WriteFile(info.FullName);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        public static string GetFileName(string str)
        {
            int num = str.LastIndexOf('\\');
            if (num != -1)
            {
                return str.Substring(num + 1);
            }
            return "";
        }

        public static string GetSuffix(string _srcName)
        {
            int startIndex = _srcName.LastIndexOf(".");
            if (startIndex != -1)
            {
                _srcName = _srcName.ToLower().Substring(startIndex);
                return _srcName;
            }
            _srcName = ".uitv";
            return _srcName;
        }

        public static string ReadPageModel(string modelAbsPath)
        {
            return ReadPageModel(modelAbsPath, Encoding.Default);
        }

        public static string ReadPageModel(string modelAbsPath, Encoding encoding)
        {
            string str;
            try
            {
                StringBuilder builder = new StringBuilder();
                using (StreamReader reader = new StreamReader(modelAbsPath, encoding))
                {
                    builder.Append(reader.ReadToEnd());
                }
                str = builder.ToString();
            }
            catch (Exception exception)
            {
                throw new Exception("读出模板'" + modelAbsPath + "'失败。错误信息：" + exception.Message);
            }
            return str;
        }

        public static void RemoveFile(string _src)
        {
            try
            {
                if (File.Exists(_src))
                {
                    File.Delete(_src);
                }
            }
            catch (Exception exception)
            {
                throw new Exception("删除文件'" + _src + "'失败。错误信息：" + exception.Message);
            }
        }

        public static void ReNameFile(string _src, string _newName)
        {
            try
            {
                int length = _src.LastIndexOf(@"\");
                if (length != -1)
                {
                    string destFileName = _src.Substring(0, length) + @"\" + _newName + GetSuffix(_src);
                    if (File.Exists(_src))
                    {
                        File.Copy(_src, destFileName, true);
                        File.Delete(_src);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new Exception("重命名文件'" + _src + "'失败。错误信息：" + exception.Message);
            }
        }

        public static void SaveFileToServer(HttpPostedFile _file, string fileLocalPath, ref string _absPath)
        {
            try
            {
                DateTime now = DateTime.Now;
                _absPath = now.ToShortDateString().Replace("-", "") + @"\";
                if (!Directory.Exists(fileLocalPath + _absPath))
                {
                    Directory.CreateDirectory(fileLocalPath + _absPath);
                }
                _absPath = _absPath + Guid.NewGuid() + GetSuffix(_file.FileName);
                _file.SaveAs(fileLocalPath + _absPath);
                _absPath = _absPath.Replace(@"\", "/");
            }
            catch (Exception exception)
            {
                throw new Exception("保存文件'" + fileLocalPath + "'失败。错误信息：" + exception.Message);
            }
        }

        public static void UpdateFile(string _content, string path)
        {
            UpdateFile(_content, path, Encoding.Default);
        }

        public static void UpdateFile(string _content, string path, Encoding encoding)
        {
            try
            {
                path = path.Replace("/", @"\");
                int length = path.LastIndexOf(@"\");
                if (length != -1)
                {
                    string str = path.Substring(0, length);
                    if (!Directory.Exists(str))
                    {
                        Directory.CreateDirectory(str);
                    }
                    using (FileStream stream = new FileStream(path, FileMode.Create))
                    {
                        byte[] bytes = encoding.GetBytes(_content);
                        stream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new Exception("创建文件'" + path + "'失败。错误信息：" + exception.Message);
            }
        }
    }
}

